from django.shortcuts import render
from django.http import HttpResponse
import os,re
# Create your views here.
from rest_framework.viewsets import ModelViewSet
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from django.db.models import Count
from django.db.models import Q
from django.utils.timezone import now
from django.utils import timezone
from django.contrib.auth.models import User

from rest_framework import filters
from rest_framework import mixins
from rest_framework import permissions
# from rest_framework import authentication
from rest_framework import status
from rest_framework import viewsets
# from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

#导入分页模块并改写
from rest_framework import filters
from rest_framework.pagination import PageNumberPagination
from rest_framework import permissions
from bookshelf.getbook import geturl
class CommonPagination(PageNumberPagination):
    """
    通用分页配置类
    """
    # 每页的记录数
    page_size = 50
    # url中请求“页”的参数名
    page_query_param = 'page'
    # url中请求“每页记录数”的参数名
    page_size_query_param = 'page_size'
    # 每页最大记录数
    max_page_size = 200


#从应用模块的models文件中导入对应模型[表单]
from bookshelf.models import Book
#从应用模块的serializers文件中导入对应模型Serializer
from bookshelf.serializers import BookSerializer
 
def runoob(request):
    # context          = {}
    # context['hello'] = 'Hello World!'
    name = request.GET.get("name")
    num_ = request.GET.get("num")
    num = str(num_).replace('.html','')
    return render(request, os.path.dirname(__file__) + os.sep + '..' + os.sep + 'media' + os.sep + 'book' + os.sep + name + os.sep + num +'.html')

    # return render(request, os.path.dirname(__file__) + os.sep + '..' + os.sep + 'media' + os.sep + 'book' +r'\庆云仙\630845.html', context)

def showurl(request): 
    name = request.GET.get("name")
    library = ''
    if name:
        filelist = os.listdir(os.path.dirname(__file__) + os.sep + '..' + os.sep + 'media' + os.sep + 'book' + os.sep + name)  # 该文件夹下所有的文件（包括文件夹）
        for files in filelist:
            library=library+str(files)+':'+'&nbsp;&nbsp;&nbsp;&nbsp;'+'http://公网IP:端口' + '/book/?name=' + name +   '&num=' + str(files).replace('.html','') + '<br>' 
    else:
        filelist = os.listdir(os.path.dirname(__file__) + os.sep + '..' + os.sep + 'media' + os.sep + 'book')  # 该文件夹下所有的文件（包括文件夹）
        for files in filelist:
            Olddir = os.path.join(os.path.dirname(__file__) + os.sep + '..' + os.sep + 'media' + os.sep + 'book', files)
            if os.path.isdir(Olddir):
                library=library+str(files)+':'+'&nbsp;&nbsp;&nbsp;&nbsp;'+'http://公网IP:端口' + '/library/?name=' + str(files)

    return HttpResponse(library)
class BookViewSet(ModelViewSet):
    """
    小说模型<br>
    抓取来源：https://www.kuwx.net/ <br>
    书页路径：/library
    """

    serializer_class = BookSerializer
    permission_classes = [permissions.IsAuthenticated]
    # 分页+统计
    pagination_class = CommonPagination

    def create(self, request, *args, **kwargs):
        if "name" in request.data and 'url' in request.data:
            geturl(request.data["name"],request.data["url"])

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        if "name" in request.data and 'url' in request.data:
            geturl(request.data["name"],request.data["url"])
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

    def get_queryset(self, *args, **kwargs):

        return Book.objects.filter(deleted__exact='0')
    

    def destroy(self, request, *args, **kwargs):
        """
        销毁模型实例.
        """
        instance = self.get_object()
        # 永久删除
        # self.perform_destroy(instance)
        # 临时删除  假删除
        instance.deleted = 1
        instance.save()
        context = {
            'code': status.HTTP_204_NO_CONTENT,
            'msg': '删除成功！',
            'data': ''
        }
        # 如果反馈“HTTP_204_NO_CONTENT”，会导致context中内容没有返回给浏览器
        return Response(context, status=status.HTTP_200_OK)